from flask import current_app
from flask import redirect, jsonify
from flask import request

from info import constants
from info import db
from info.models import News, Category, User
from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import user_blue
from flask import render_template, g
from info.utils.common import user_login_data


@user_blue.route("/info")
@user_login_data
def get_user_info():
    user = g.user
    if not user:
        return redirect("/")
    data = {
        "user_info": user.to_dict() if user else None,
    }
    return render_template("news/user.html", data=data)


@user_blue.route("/base_info", methods=["GET", "POST"])
@user_login_data
def base_info():
    user = g.user
    if request.method == "GET":
        data = {
            "user_info": user.to_dict() if user else None,
        }
        return render_template("news/user_base_info.html", data=data)
    signature = request.json.get("signature")
    nick_name = request.json.get("nick_name")
    gender = request.json.get("gender")
    # if all([signature,nick_name,gender]):
    #     return jsonify(errni=RET.PARAMERR,errmsg="参数错误")
    user.signature = signature
    user.nick_name = nick_name
    user.gender = gender
    db.session.commit()
    return jsonify(errno=RET.OK, errmsg="资料修改成功")


@user_blue.route("/pic_info", methods=["GET", "POST"])
@user_login_data
def pic_info():
    user = g.user
    if request.method == "GET":
        return render_template('news/user_pic_info.html', data={"user_info": user.to_dict()})
    avatar_url = request.files.get("avatar").read()
    key = storage(avatar_url)
    user.avatar_url = key
    db.session.commit()
    data = {
        "avatar_url": constants.QINIU_DOMIN_PREFIX + key
    }
    return jsonify(errno=RET.OK, errmsg="头像上传成功", data=data)


@user_blue.route("/pass_info", methods=["GET", "POST"])
@user_login_data
def pass_info():
    user = g.user
    if request.method == "GET":
        return render_template('news/user_pass_info.html')
    old_password = request.json.get("old_password")
    new_password = request.json.get("new_password")
    if not user.check_password(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="密码错误")
    user.password = new_password
    db.session.commit()
    return jsonify(errno=RET.OK, errmsg="密码修改成功")


@user_blue.route("/collection")
@user_login_data
def collection():
    user = g.user
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        p = 1
    paginate = user.collection_news.paginate(p, 3, False)
    items = paginate.items
    current_page = paginate.page
    total_page = paginate.pages
    collection_list = []
    for collection in items:
        collection_list.append(collection.to_review_dict())
    data = {
        "collections": collection_list,
        "current_page": current_page,
        "total_page": total_page
    }
    return render_template("news/user_collection.html", data=data)


@user_blue.route("/news_release", methods=["GET", "POST"])
@user_login_data
def news_release():
    user = g.user
    if request.method == "GET":
        categorys = Category.query.all()
        category_list = []
        for category in categorys:
            category_list.append(category.to_dict())
        category_list.pop(0)
        return render_template('news/user_news_release.html', data={"categories": category_list})
    title = request.form.get("title")
    category_id = request.form.get("category_id")
    digest = request.form.get("digest")
    index_image = request.files.get("index_image").read()
    content = request.form.get("content")
    source = "个人发布"
    key = storage(index_image)
    news = News()
    news.title = title
    news.category_id = category_id
    news.digest = digest
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.content = content
    news.status = 1
    news.user_id = user.id
    news.source = source
    db.session.add(news)
    db.session.commit()
    return jsonify(errno=RET.OK, errmsg="文章发布成功")


@user_blue.route("/news_list")
@user_login_data
def news_list():
    user = g.user
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        p = 1
    paginate = News.query.filter(News.user_id == user.id).paginate(p, 3, False)
    items = paginate.items
    current_page = paginate.page
    total_page = paginate.pages
    news_list = []
    for news in items:
        news_list.append(news.to_review_dict())
    data = {
        "news_list": news_list,
        "current_page": current_page,
        "total_page": total_page
    }
    return render_template("news/user_news_list.html", data=data)


@user_blue.route("/user_follow")
@user_login_data
def user_follow():
    user = g.user
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        p = 1
    paginate = user.followed.paginate(p, 4, False)
    items = paginate.items
    current_page = paginate.page
    total_page = paginate.pages
    other_list = []
    for item in items:
        other_list.append(item.to_dict())
    data = {
        "users": other_list,
        "current_page": current_page,
        "total_page": total_page
    }
    return render_template("news/user_follow.html", data=data)


@user_blue.route("/other_info")
@user_login_data
def other_info():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="请登陆")
    user_id = request.args.get("id")
    other = User.query.get(user_id)
    is_followed = False
    if other and user:
        if other in user.followers:
            is_followed = True
    data = {
        "user_info": user.to_dict(),
        "other_info": other.to_dict(),
        "is_followed": is_followed
    }
    return render_template("news/other.html", data=data)


@user_blue.route("/other_news_list")
def other_news_list():
    p = request.args.get("p")
    user_id = request.args.get("user_id")
    try:
        p = int(p)
    except Exception as e:
        p = 1
        current_app.logger.error(e)
    other = User.query.get(user_id)
    paginate = News.query.filter(News.user_id == other.id).paginate(p, 10, False)
    items = paginate.items
    current_page = paginate.page
    total_page = paginate.pages
    news_list = []
    for item in items:
        news_list.append(item.to_review_dict())
    data = {
        "news_list": news_list,
        "current_page": current_page,
        "total_page": total_page
    }

    return jsonify(errno=RET.OK, errmsg="OK", data=data)
